package com.qy33.data;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.qy33.entity.Stock;
import com.qy33.util.StockUtil;

/**
 * 通达信数据dao
 * @author qy33
 * @date 2013-01-21
 * 
 */
public class StockDao {

	public static final Logger logger = Logger.getLogger(StockDao.class);

	private String tdxDir = "D:\\zd_zszq";
	private String exportDir = "D:\\stock\\data";

	public List<Stock> findByCode(String code) {
		String prefix = null;
		if (code.equals("999999") || code.startsWith("60")) {
			prefix = "sh";
		} else {
			prefix = "sz";
		}
		File file = new File(tdxDir + File.separator + "vipdoc"
				+ File.separator + prefix + File.separator + "lday"
				+ File.separator + prefix + code + ".day");
		return parseDayFile(file);
	}

	/**
	 * 解析通达信的 *.day文件
	 * @param file
	 * @return
	 */
	public List<Stock> parseDayFile(File file) {
		List<Stock> result = null; 
		if (file.exists()) {
			FileInputStream in = null;
			DataInputStream dis = null;
			try {
				in = new FileInputStream(file);
				dis = new DataInputStream(in);

				result = new ArrayList<Stock>();
				while(dis.available()>0){
					Stock stock = new Stock();
					// 日期
	                String date = parseDayFileForString(dis);  
	                stock.setDate(date);
	                
	                //开盘价 
	                BigDecimal begin = parseDayFileForAmt(dis);
	                stock.setBegin(begin);
	                
	                //最高价
	                BigDecimal high = parseDayFileForAmt(dis);  
	                stock.setHigh(high);
	                  
	                //最低价
	                BigDecimal low = parseDayFileForAmt(dis);  
	                stock.setLow(low);
	                  
	                //收盘价
	                BigDecimal end = parseDayFileForAmt(dis);
	                stock.setEnd(end);
	                
	                //不知道是什么
	                parseDayFileForString(dis);  
	  
	                //成交量
	                BigDecimal vol = parseDayFileForAmt(dis);
	                stock.setVol(vol);
	                
	                //不知道是什么
	                parseDayFileForString(dis);  
	                
	                result.add(stock);
				}

			} catch (IOException e) {
				logger.error("解析时出错" + e.getMessage(), e);
			} finally {
				try {
					dis.close();
					in.close();
				} catch (IOException e) {
					logger.error("关闭时出错" + e.getMessage(), e);
				}
			}
			
			for (Stock stock : result) {
				stock.setCode(StringUtils.substringBefore(file.getName(), "."));
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		StockDao dao = new StockDao();
		List<Stock> stockList = dao.findByCode("600537");
		for (Stock stock : stockList) {
			System.out.println(stock);
		}
	}

	private static String parseDayFileForString(DataInputStream dis)
			throws IOException {
		byte[] b1 = new byte[1];
		byte[] b2 = new byte[1];
		byte[] b3 = new byte[1];
		byte[] b4 = new byte[1];
		dis.read(b1, 0, 1);
		dis.read(b2, 0, 1);
		dis.read(b3, 0, 1);
		dis.read(b4, 0, 1);
		String s1 = StockUtil.bytesToHexString(b1);
		String s2 = StockUtil.bytesToHexString(b2);
		String s3 = StockUtil.bytesToHexString(b3);
		String s4 = StockUtil.bytesToHexString(b4);
		return String.valueOf(Long.parseLong(s4 + s3 + s2 + s1, 16));
	}

	private static BigDecimal parseDayFileForAmt(DataInputStream dis)
			throws IOException {
		byte[] b1 = new byte[1];
		byte[] b2 = new byte[1];
		byte[] b3 = new byte[1];
		byte[] b4 = new byte[1];
		dis.read(b1, 0, 1);
		dis.read(b2, 0, 1);
		dis.read(b3, 0, 1);
		dis.read(b4, 0, 1);
		String s1 = StockUtil.bytesToHexString(b1);
		String s2 = StockUtil.bytesToHexString(b2);
		String s3 = StockUtil.bytesToHexString(b3);
		String s4 = StockUtil.bytesToHexString(b4);
		return new BigDecimal(Long.parseLong(s4 + s3 + s2 + s1, 16) / 100.0)
				.setScale(2, RoundingMode.HALF_UP);
	}

	public List<Stock> findByCodeByExportFile(String code) {
		String prefix = null;
		if (code.equals("999999") || code.startsWith("60")) {
			prefix = "SH";
		} else {
			prefix = "SZ";
		}
		File file = new File(exportDir + File.separator + prefix + code);
		List<String> strList = null;
		try {
			strList = FileUtils.readLines(file);
		} catch (IOException e) {
			logger.error("文件不存在", e);
		}

		List<Stock> result = new ArrayList<Stock>();
		for (String str : strList) {
			if (StringUtils.indexOf(str, ',') == -1) {
				continue;
			}
			String[] array = str.split(",");
			Stock stock = new Stock();
			stock.setCode(prefix + code);
			stock.setDate(array[0]);
			stock.setBegin(new BigDecimal(array[1]));
			stock.setHigh(new BigDecimal(array[2]));
			stock.setLow(new BigDecimal(array[3]));
			stock.setEnd(new BigDecimal(array[4]));
			stock.setVol(new BigDecimal(array[5]));
			stock.setAmount(new BigDecimal(array[6]));

			result.add(stock);
		}
		return result;
	}

}
